package chatGUI;

import Model.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Observable;
import java.util.Observer;
import javax.swing.*;

public class ConnectWindowPanel extends JPanel implements Observer {

    Users list;
    JPanel window, chatWindow;
    JFrame chatFrame;
    JLabel loginLabel, listLabel, infoLabel, userInfoLabel, welcomeLabel;
    JButton loginButton, logoutButton;
    JTextArea chatArea;
    JTextField usernameField;
    JList jUserList;
    JFileChooser fileChooser;
    File selectedFile;
    DefaultListModel usersListModel;
    JScrollPane chatPane, inputPane, listPane;
    String formattedText, formattedUsername, selectedUser, output, userFormattedText;
    ImageIcon welcomeIcon;
    Calendar cal;
    boolean flag = true;
    int usernameSize, result, userResult;
    ChatController.ChatController cc;
    Model.Users users;
    Boolean first =true;

    public JTextArea getChatArea() {
        return chatArea;
    }

    public void update(Observable o, final Object a) {




        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                HashMap a2 = (HashMap) a;
                usersListModel.removeAllElements();
                Set cles = a2.keySet();
                Iterator it = cles.iterator();

                while (it.hasNext()) {
                    Object cle = it.next();
                    InetAddress cle2 = (InetAddress) cle;
                    Object pers = a2.get(cle2);
                    User pers2 = (User) pers;

                    usersListModel.addElement(pers2.toString());
                }
                validate();
                repaint();
            }
        });






    }

    public ConnectWindowPanel(ChatController.ChatController cc) {
        this.cc = cc;
        this.users = cc.getUserList();
        window = new JPanel();
        initializeWelcomeScreen();
        usersListModel = new DefaultListModel();
        this.list = cc.getUserList();
        list.addObserver(this);
        jUserList = new JList(usersListModel);
        jUserList.addMouseListener(new MouseL());

    }

    public void initializeWelcomeScreen() {
        // window.setBorder(new TitledBorder(new EtchedBorder(), "Developed by Anthony Doutre and Georges Aoun "));
        welcomeIcon = new ImageIcon("Library/Gajim-logo.png");
        welcomeLabel = new JLabel();
        welcomeLabel.setIcon(welcomeIcon);
        window.addMouseListener(new MouseListener() {
            @Override
            public void mouseReleased(MouseEvent arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mouseEntered(MouseEvent arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mouseClicked(MouseEvent arg0) {
                if (flag) {
                    initializeWindowPanel();
                    repaint();
                }
            }
        });

        window.add(welcomeLabel);
        window.setPreferredSize(new Dimension(700, 620));
        add(window);
    }

    public void initializeWindowPanel() {
        flag = false;
        welcomeLabel.setVisible(false);
        loginButton = new JButton("Connect");
        loginButton.addActionListener(new ButtonListener());
        loginButton.setMnemonic('c');
        loginLabel = new JLabel("Enter your Username:");
        window.setLayout(new BorderLayout());
        usernameField = new JTextField();
        window.add(loginLabel, BorderLayout.NORTH);
        window.add(usernameField, BorderLayout.CENTER);
        window.add(loginButton, BorderLayout.SOUTH);
        window.setPreferredSize(new Dimension(300, 100));
        revalidate();
        add(window);
    }

    public void initializeChatPanel() {
        window.setLayout(null);
        window.setPreferredSize(new Dimension(700, 620));
        window.setBackground(Color.LIGHT_GRAY);
        listPane = new JScrollPane(jUserList);
        listPane.setBounds(437, 78, (675 - 447), (544 - 78));
        listPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        logoutButton = new JButton("Disconnect");
        logoutButton.setBounds(559, 557, (677 - 559), 28);


        logoutButton.setMnemonic('d');
        logoutButton.addActionListener(new ButtonListener());


        this.chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);

        chatPane = new JScrollPane(chatArea);
        chatPane.setBounds(20, 78, (413 - 30), (544 - 78));
        chatPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        loginLabel = new JLabel("Welcome " + usernameField.getText() + " to the chat system.");
        loginLabel.setBounds(23, 17, (414 - 23), (65 - 17));
        listLabel = new JLabel("List of Connected Users");
        listLabel.setForeground(Color.RED);
        listLabel.setBounds(444, 34, (675 - 447), (62 - 26));
        infoLabel = new JLabel();
        infoLabel.setBounds(20, 546, (413 - 30), 20);
        window.add(chatPane);
        window.add(listPane);
        window.add(loginLabel);
        window.add(logoutButton);

        window.add(listLabel);
        window.add(infoLabel);
        revalidate();
        add(window);
    }

    private class MouseL implements MouseListener {

        @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int pos = jUserList.getSelectedIndex();
                formattedUsername = usernameField.getText().trim();
                // if (!(selectedUser.equals(" " + formattedUsername))) {

                ChatWindow w = cc.getUserList().nouv_conv((User) cc.getIndex(pos), cc);
                // }

            }
        }
    }

    private class ButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == (loginButton)) {
               
                formattedUsername = usernameField.getText().trim(); //get rid of empty spaces at the beginning
                usernameSize = usernameField.getText().length();
                if (formattedUsername.isEmpty()) //check if username area is empty
                {
                    JOptionPane.showMessageDialog(null, "Please enter your username below", "Enter a valid Username", 0);
                } else if (usernameSize > 12) {
                    JOptionPane.showMessageDialog(null, "Username cannot exceed 12 characters", "Enter a valid Username", 2);
                } else {
                    window.removeAll();
                    initializeChatPanel();
                    repaint();
                    try {
                     
                        cc.demarre();
                     
                        chatNI.ChatNI.sendHello(formattedUsername, true);
                        User localUser = new User(formattedUsername, InetAddress.getLocalHost());
                        cc.setLocalUser(localUser);

                    } catch (SocketException err) {
                        System.err.print(err);
                    } catch (UnknownHostException u) {
                        System.err.print(u);
                    }


                }
            }
            if (e.getSource() == logoutButton) {

                try {
                    chatNI.ChatNI.sendBye();
                } catch (SocketException err) {
                    System.err.print(err);
                } catch (UnknownHostException u) {
                    System.err.print(u);
                }
                cc.close_sock();
                cc.setRunning(false);
                cc.setRec(null);
                cc.stop();
                usersListModel.clear();
                window.removeAll();
                initializeWindowPanel();
                repaint();
            }





        }
    }
     public Boolean dialog(String username, String filename) {
        int dialogButton = JOptionPane.YES_NO_OPTION;
        int dialog = JOptionPane.showConfirmDialog(null, username +" wants to send "+ filename +"\nAccept?", "Warning", dialogButton);
        if (dialog == JOptionPane.YES_OPTION) {
            return true;
        }
        return false;
    }
}
